package cn.sciento.starter.social.wechat.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import cn.sciento.starter.social.core.common.api.AbstractSocialApi;
import cn.sciento.starter.social.core.exception.ProviderUserNotFoundException;
import cn.sciento.starter.social.core.provider.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;

public class DefaultWechatApi extends AbstractSocialApi implements WechatApi {
  private static final Logger LOGGER = LoggerFactory.getLogger(DefaultWechatApi.class);
  
  private static final ObjectMapper mapper = new ObjectMapper();
  
  private String userInfoUrl;
  
  public DefaultWechatApi(String accessToken, Provider provider) {
    super(accessToken);
    this.userInfoUrl = provider.getUserInfoUrl() + "?openid={openId}";
  }
  
  public WechatUser getUser(String providerUserId) {
    String result = (String)getRestTemplate().getForObject(this.userInfoUrl, String.class, new Object[] { providerUserId });
    WechatUser user = null;
    try {
      user = (WechatUser)mapper.readValue(result, WechatUser.class);
    } catch (Exception e) {
      LOGGER.error("parse wechat UserInfo error. result : {}", result);
    } 
    if (user == null || StringUtils.isBlank(user.getNickname())) {
      LOGGER.info("not found provider user, result user={}", user);
      throw new ProviderUserNotFoundException("hoth.social.providerUserNotFound");
    } 
    return user;
  }
  
  protected List<HttpMessageConverter<?>> getMessageConverters() {
    List<HttpMessageConverter<?>> converters = super.getMessageConverters();
    converters.remove(0);
    converters.add(new StringHttpMessageConverter(Charsets.UTF_8));
    return converters;
  }
}
